#include "SphereSceneNode.h"
#include "../include/CTypes.h"
#include "../include/ISceneNode.h"
#include "../include/PowerLibraryEngine.h"

CSphereSceneNode::CSphereSceneNode(CSceneGenerator *sgen,vector3dvpos Radius,u32 Partitions,ISceneNodeReceiveParams):
IDrawableSceneNode(ISceneNodeBasicParams)
{
	Partitions = 20;
	vector3dvpos Master(0.0,Radius.Y,0.0);
	vector3dvpos Inc((vPos)180.0 / (vPos)Partitions,(vPos)180.0 / (vPos)Partitions,(vPos)180.0 / (vPos)Partitions);

	IMatrix3D<vPos> matrix(MCF_IDENTITY);
	matrix.SetRotationDegrees(vector3d<vPos>(0.0,0.0,Inc.Z));

	std::vector<std::vector<vector3dvpos> > StoreVectors;

	for (u32 i=0;i<Partitions;i++)
	{
		// Create an empty vector data to store the vectors.
		std::vector<vector3dvpos> VectorToSave;
		vector3dvpos VActualCopy(Master);
		// The first value is always the same with the rotation of that y.
//		VectorToSave.push_back(VActualCopy);
		// Create an identity matrix.
		IMatrix3D<vPos> matrix1(MCF_IDENTITY);
		IMatrix3D<vPos> matrix2(MCF_IDENTITY);
		// Set the rotation in the z increment and the y increment that follows.

		for (u32 j=0;j<Partitions;j++)
		{
			matrix1.SetRotationDegrees(vector3d<vPos>(0.0,0.0,(vPos)j*Inc.Z));
			matrix2.SetRotationDegrees(vector3d<vPos>(0.0,(vPos)(Inc.Y*i),0.0));
			vector3dvpos VActual(VActualCopy);
			VActual = matrix1 * VActual;
			VActual = matrix2 * VActual;
			VectorToSave.push_back(VActual);
		}

		// We store the generated vector.
		StoreVectors.push_back(VectorToSave);
	}

	for (u32 i=0;i<StoreVectors.size()-1;i++)
	{
		for (u32 j=0;j<StoreVectors[i].size()-1;j++)
		{
			vector3dvpos v1(StoreVectors[i][j+1]);
			vector3dvpos v2(StoreVectors[i+1][j+1]);
			vector3dvpos v3(StoreVectors[i+1][j]);
			vector3dvpos v4(StoreVectors[i][j]);
			IDrawableFace *detemp = new IDrawableFace(4);
			detemp->BeginVectors();
			detemp->AddVector(&v1);
			detemp->AddVector(&v2);
			detemp->AddVector(&v3);
			detemp->AddVector(&v4);
			detemp->EndVectors();
			de.push_back(detemp);
		}
	}

	BBox.SetBoundingBox(de);
}

CSphereSceneNode::~CSphereSceneNode()
{

}

void CSphereSceneNode::Render(IDrawableFaceManager *dfm)
{
	for (u32 i=0;i<de.size();i++)
	{
		dfm->AddToRenderList3D(de[i]);
	}
}
